package servlets;

import hibernatelogic.HibUsers;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import orm.Users;

@WebServlet("/delete-user-servlet")
public class DeleteUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger loggerDeleteUserServlet = Logger
			.getLogger(DeleteUserServlet.class);

	public DeleteUserServlet() {
		super();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession sess = request.getSession();
		
		/*
		 * Are you really an administrator?
		 */
		if (((String) sess.getAttribute("UserRole")).equals("3")) {
			
			HibUsers hibUsers = new HibUsers();
			Users user = new Users();
			
			/*
			 * What user do you want to delete?
			 */
			int user_id = Integer.parseInt(request.getParameter("duser"));
			
			try {
				/*
				 * Get that user and delete him
				 */
				user = hibUsers.getUserByID(user_id);
				hibUsers.deleteUser(user);
			} catch (SQLException e) {
				loggerDeleteUserServlet.error(
						"Something wrong with DeleteUserServlet", e);
			} finally {
				/*
				 * Destroy and redirect
				 */
				hibUsers = null;
				user = null;
				response.sendRedirect("/my-pet-project-0/ADeleteUser.jsp");
			}

			/*
			 * If you are not an administrator, then go away
			 */
		} else {
			response.sendError(response.SC_FORBIDDEN);
		}
	}
}
